package com.cicadasmall.datasource.aspect;

import com.cicadasmall.datasource.annotation.SwitchDataSource;
import com.cicadasmall.datasource.datasorce.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;

/**
 * 数据源切换切面
 *
 * @author Jin
 */
@Slf4j
@Aspect
@Order(-1)
public class DataSourceAspect {


    @Before("@annotation(ds)")
    public void changeDataSource(JoinPoint point, SwitchDataSource ds) {
        String name = ds.name();
        try {
            DynamicDataSourceContextHolder.setDataSourceType(name);
        } catch (Exception e) {
            log.error("数据源[{}]不存在，使用默认数据源 > {}", ds.name(), point.getSignature());
        }


    }

    @After("@annotation(ds)")
    public void restoreDataSource(JoinPoint point, SwitchDataSource ds) {
        log.debug("Revert DataSource : {} > {}", ds.name(), point.getSignature());
        DynamicDataSourceContextHolder.clearDataSourceType();
    }

}